package de.windeln.marketing.validation;

import java.lang.annotation.Annotation;

import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import de.windeln.marketing.campaign.model.RequestClientObject;

@ControllerAdvice
public class ValidatorHandlerAdvice {

	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseStatus(org.springframework.http.HttpStatus.BAD_REQUEST)
	public @ResponseBody
	ErrorEntities handleException(MethodArgumentNotValidException exception,
			HttpServletResponse response) {

		ErrorEntities errorEntities = new ErrorEntities();
		for (ObjectError error : exception.getBindingResult().getAllErrors()) {
			String propertyName = error.getObjectName();

			if (error instanceof FieldError) {
				FieldError fieldError = (FieldError) error;
				Annotation[] fieldAnnotations = AnnotationIntrospector
						.findFieldAnnotation(RequestClientObject.class,
								fieldError.getField());

				if (fieldAnnotations != null) {
					for (Annotation annotation : fieldAnnotations) {
						if (annotation.annotationType() == com.fasterxml.jackson.annotation.JsonProperty.class) {
							propertyName = ((com.fasterxml.jackson.annotation.JsonProperty) annotation)
									.value();
						}
					}
				}
			}else{
				propertyName = error.getCode();
			}
			errorEntities.addError(propertyName, error.getDefaultMessage());
		}
		// set the response status
		response.setStatus(HttpStatus.BAD_REQUEST.value());
		return errorEntities;
	}

}
